<template>
    <!-- 表格间距需要缩短 -->
    <div class="app-container">
        <div id="examineProgress">
            <span>当前共有</span>
            <span>{{workStatues.notExamined}} 份待审核</span>
            <span>{{workStatues.alreadyExamined}} 份已审核</span>
            <span>{{workStatues.notSubmitted}} 份未提交</span>
        </div>
        <el-form :model="filter">
            <el-row :gutter="10">
                <el-col :span="16">
                    <el-form-item label="审核状态" label-width="100px" class="item1">
                        <el-radio-group v-model="filter.examineStatusCode" @input="radio_change">
                            <el-radio :label="0">全部</el-radio>
                            <el-radio :label="1">待审核</el-radio>
                            <el-radio :label="2">已审核</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="5" :offset="1">
                    <el-form-item label="搜索" label-width="80px" class="item1">
                        <el-input v-model="filter.search" placeholder="请输入内容" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2" align="right">
                    <el-form-item class="item1">
                        <el-button type="primary" icon="el-icon-search" size="medium" @click="selectByName">查询</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="10">
                <el-col :span="5">
                    <el-form-item label="企业所在市" label-width="100px" class="item2">
                        <el-select v-model="filter.city" placeholder="全部" @change="selectChange">
                            <el-option v-for="city in cities" :label="city" :value="city">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="调查期" label-width="100px" class="item2">
                        <el-select v-model="filter.investigation" placeholder="全部" @change="selectChange">
                            <el-option v-for="investigation in investigations" :label="investigation" :value="investigation">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
				<el-col :span="2.2" :offset="9" align="left">
					<el-form-item class="item2">
						<el-button type="text" @click="completeAllBlankEntries" style="font-size: 15px;" v-if="roleId == 1"
								   >一键填充未填报表</el-button>
					</el-form-item>
				</el-col>
				<el-col :span="1" align="center" style="width: 15px;">
					<el-form-item label="|" label-width="22px" style="font-size: 15px" class="item2" v-if="roleId == 1"></el-form-item>
				</el-col>
                <el-col :span="1" align="left">
                    <el-form-item class="item2">
                        <el-button type="text" @click="passPatch" style="font-size: 15px;"
                            :disabled="!selected.multiSelectFlag">一键通过</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="1" align="center" style="width: 15px;">
                    <el-form-item label="|" label-width="22px" style="font-size: 15px" class="item2"></el-form-item>
                </el-col>
                <el-col :span="1" align="left">
                    <el-form-item class="item2">
                        <el-button type="text" @click="returnBackPatch" style="font-size: 15px;"
                            :disabled="!selected.multiSelectFlag">一键退回</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-table v-loading="listLoading" :data="showData" element-loading-text="Loading" border fit highlight-current-row
            :cell-style="{ padding: '3px 0' }" :row-class-name="tableRowClassName" header-cell-class-name="table_header"
            @selection-change="handleSelectionChange" :row-key="getRowKey" ref="inOrderTable">

            <el-table-column type="selection" :selectable="(row, index) => row.formExamineStatus == notExaminedStatusCode"
                width="45" align="center" :reserve-selection="true"></el-table-column>

            <el-table-column label="企业名" width="250" align="center">
                <template slot-scope="scope">
                    {{ scope.row.formCompanyName }}
                </template>
            </el-table-column>

            <el-table-column label="调查期" width="150" align="center">
                <template slot-scope="scope">
                    {{ scope.row.formInvestigationName }}
                </template>
            </el-table-column>

            <el-table-column label="建档期就业人数" width="120" align="center">
                <template slot-scope="scope">
                    {{ scope.row.formStartTotalNum != null ? scope.row.formStartTotalNum : scope.row.formEndTotalNum }}
                </template>
            </el-table-column>

            <el-table-column label="调查期就业人数" width="140" align="center">
                <template slot-scope="scope">
                    {{ scope.row.formEndTotalNum }}
                </template>
            </el-table-column>

            <el-table-column label="就业人数减少类型" width="150" align="center">
                <template slot-scope="scope">
                    {{ scope.row.formDecreaseType }}
                </template>
            </el-table-column>

            <el-table-column label="主要原因" width="130" align="center">
                <template slot-scope="scope">
                    {{ scope.row.formFirstReason }}
                </template>
            </el-table-column>

            <el-table-column label="提交时间" width="150" align="center">
                <template slot-scope="scope">
                    {{ scope.row.formSubmitTime }}
                </template>
            </el-table-column>

            <el-table-column label="审核状态" width="100" align="center">
                <template slot-scope="scope">
                    {{ scope.row.formExamineStatus < notExaminedStatusCode ? "未提交" : scope.row.formExamineStatus == notExaminedStatusCode + 1 ? "已审批退回" : (scope.row.formExamineStatus >= notExaminedStatusCode + 2 && scope.row.formExamineStatus < 7) ? "已审批通过" : scope.row.formExamineStatus == 7 ? "已上报国家" : "未审批" }}
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="200" align="center">
                <template slot-scope="scope">
					<el-button @click="showEdit(scope.row)" type="text" :disabled="scope.row.formExamineStatus >= 6" v-if="roleId == 1">修改</el-button>
                    <el-button @click="showForm(scope.row)" type="text" :disabled="scope.row.formExamineStatus < notExaminedStatusCode">查看</el-button>
                    <el-button @click="passSingle(scope.row)" type="text" :disabled="selected.multiSelectFlag || scope.row.formExamineStatus !== notExaminedStatusCode">通过</el-button>
                    <el-button @click="returnBackSingle(scope.row)" type="text" :disabled="selected.multiSelectFlag || scope.row.formExamineStatus !== notExaminedStatusCode">退回</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="changePageSize" @current-change="changeCurrentPage" :current-page="page.currentPage"
            :page-sizes="[10, 20, 50]" :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="page.totalItems">
        </el-pagination>

		<el-dialog title="修改/自动填写数据" :visible.sync="editDialog.showFlag" v-if="editDialog.showFlag" width="80%">
			<div>
				<edit-dialog-form :entry="entry"></edit-dialog-form>
			</div>
		</el-dialog>

        <el-dialog title="数据报表信息" :visible.sync="showingForm.showFlag" width="40%" top="20vh">
            <div class="formDetailTitle">
                {{ showingForm.data.formCompanyName }}
            </div>
            <el-row>
                <el-col :span="17">
                    <el-form :model="showingForm.data">
                        <el-row>
                            <el-col :span="20" :offset="1">
                                <el-form-item label="建档期就业人数" label-width="140px">
                                    {{ showingForm.data.formStartTotalNum != null ? showingForm.data.formStartTotalNum : showingForm.data.formEndTotalNum}}
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="20" :offset="1">
                                <el-form-item label="调查期就业人数" label-width="140px">
                                    {{ showingForm.data.formEndTotalNum}}
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row v-if="showingForm.data.formDecreaseType != null && showingForm.data.formDecreaseType != ''">
                            <el-col :span="20" :offset="1">
                                <el-form-item label="就业人数减少类型" label-width="140px">
                                    {{ showingForm.data.formDecreaseType}}
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row v-if="showingForm.data.formFirstReason != null && showingForm.data.formFirstReason != ''">
                            <el-col :span="20" :offset="1">
                                <el-form-item label="主要原因" label-width="140px">
                                    {{ showingForm.data.formFirstReason}}
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row v-if="showingForm.data.formSecondReason != null && showingForm.data.formSecondReason != ''">
                            <el-col :span="20" :offset="1">
                                <el-form-item label="次要原因" label-width="140px">
                                    {{ showingForm.data.formSecondReason}}
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row v-if="showingForm.data.formThirdReason != null && showingForm.data.formThirdReason != ''">
                            <el-col :span="20" :offset="1">
                                <el-form-item label="第三原因" label-width="140px">
                                    {{ showingForm.data.formThirdReason}}
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row v-if="showingForm.data.formReasonDescription != null && showingForm.data.formReasonDescription != ''">
                            <el-col :span="20" :offset="1">
                                <el-form-item label="原因说明" label-width="140px">
                                    {{ showingForm.data.formReasonDescription}}
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-col>
                <el-col :span="7" style="border-left: 1px solid black;">
                    <div class="dialogDiv2">
                        <el-timeline>
                            <el-timeline-item
                                v-for="(activity, index) in activities"
                                :key="index"
                                :icon="activity.icon"
                                :type="activity.type"
                                :color="activity.color"
                                size="large"
                            >
                                <p class="timeline-name">{{ activity.name }}</p>
                                <p class="timeline-content" v-if="activity.idea != ''">
                                <span>备注: </span><span class="timeline-content__idea">{{ activity.idea }}</span>
                                </p>
                                <p class="timeline-content">{{ activity.timestamp }}</p>
                            </el-timeline-item>
                        </el-timeline>
                    </div>
                </el-col>
            </el-row>
        </el-dialog>
        <el-dialog title="退回备注" :visible.sync="returnBackForm.showFlag" width="35%">
            <el-form :model="returnBackForm.data">
                <el-row>
                    <el-col :span="14">
                        <el-form-item label="退回原因" label-width="80px">
                            <el-select v-model="returnBackForm.data.reason" placeholder="请选择">
                                <el-option v-for="reason in returnBackReasons" :label="reason" :value="reason">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="returnBackForm.data.reason == '其他'">
                    <el-col :span="18">
                        <el-form-item label="其他原因" label-width="80px">
                            <el-input type="textarea" :autosize="{ minRows: 0, maxRows: 4}"
                                placeholder="请输入内容"
                                v-model="returnBackForm.data.otherReasonDescription">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="returnBack" :disabled="this.returnBackForm.data.reason == '' || (this.returnBackForm.data.reason == '其他' && this.returnBackForm.data.otherReasonDescription == '')">确 定</el-button>
                <el-button @click="returnBackForm.showFlag = false">取 消</el-button>
            </span>
        </el-dialog>
        <el-dialog title="通过" :visible.sync="passConfirm.showFlag" width="35%">
            <el-form>
                <el-row>
                    <el-col :span="24">
                        确认通过数据报表吗？
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="pass">确 定</el-button>
                <el-button @click="passConfirm.showFlag = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getAllForms, passForm, returnBackForm } from '@/api/province/dataFormExamine'
import { getRoleId, getUserId } from '@/utils/auth'
import { getDataReportFormHistory } from '@/api/common/queryHistory'
import EditDialogForm from "./editDialogForm.vue";
import {autoCompleteAllBlankEntries} from "@/api/province/formEdit";

export default {
	components: {EditDialogForm},
    data() {
        return {
            userId: -1,
			roleId: -1,
            notExaminedStatusCode: 4,
            workStatues: {
                notSubmitted: 0,
                notExamined: 0,
                alreadyExamined: 0
            },
            totalData: [],
            showData: [],
            filteredData: [],
            listLoading: true,
            page: {
                currentPage: 1,
                pageSize: 10,
                totalItems: 25,
            },
            cities: [],
            investigations: [],
            filter: {
                city: '全部',
                examineStatusCode: 0,
                search: '',
                investigation: '全部'
            },
            showingForm: {
                showFlag: false,
                data: {
                    formID: '',
                    formCompanyName: '',
                    formCompanyCity: '',
                    formInvestigationName: "",
                    formStartTotalNum: '',
                    formEndTotalNum: '',
                    formDecreaseType: '',
                    formFirstReason: '',
                    formSecondReason: '',
                    formThirdReason: '',
                    formReasonDescription: '',
                    formExamineStatus: '',
                    formSubmitTime: ''
                },
            },
			editDialog: {
				showFlag: false,
			},
            selected: {
                selectedNum: 0,
                selectedItems: [],
                multiSelectFlag: false
            },
            returnBackReasons: ['数据不实', '就业人数减少原因有误', '就业人数减少原因说明不清晰', '其他'],
            returnBackForm: {
                showFlag: false,
                data: {
                    reason: '',
                    otherReasonDescription: ''
                }
            },
            returnBackData: {
                items: [],
                comments: null
            },
            passConfirm: {
                showFlag: false
            },
            passSuccess: false,
            returnBackSuccess: false,
            activities: [],
            entry: null,
        }
    },
    created() {
        this.notExaminedStatusCode = getRoleId() == 1 ? 4 : 2
        this.userId = getUserId()
		this.roleId = getRoleId()
        // console.log("created:")prop="_second_reason"
        // console.log(this.userId)
        // console.log(this.notExaminedStatusCode)
        this.initialize()

    },
    methods: {
		completeAllBlankEntries(){
			this.$confirm('确定要一键填充吗？这一操作可能需要较长时间，请耐心等待“完成”信息弹出！', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.listLoading = true
				autoCompleteAllBlankEntries({}).then(() => {
					this.$message("已完成！")
					this.listLoading = false
				})
			})
		},

        dateCmp(a, b) {
            if (new Date(a.formSubmitTime).getTime() > new Date(b.formSubmitTime).getTime()) {
                return -1
            } else {
                return 1
            }
        },

        cmp(a, b) {
            if (a.formExamineStatus == this.notExaminedStatusCode && b.formExamineStatus !== this.notExaminedStatusCode) {
                return -1
            } else if (a.formExamineStatus !== this.notExaminedStatusCode && b.formExamineStatus == this.notExaminedStatusCode) {
                return 1
            } else {
                if (a.formExamineStatus > this.notExaminedStatusCode && b.formExamineStatus < this.notExaminedStatusCode) {
                    return -1
                } else if (a.formExamineStatus < this.notExaminedStatusCode && b.formExamineStatus > this.notExaminedStatusCode) {
                    return 1
                } else {
                    return this.dateCmp(a, b)
                }
            }
        },

        getWorkStatues() {
            this.workStatues.notSubmitted = 0
            this.workStatues.notExamined = 0
            this.workStatues.alreadyExamined = 0
            var len = this.totalData.length
            // console.log(len)
            for (var i = 0; i < len; ++i) {
                if (this.totalData[i].formExamineStatus == this.notExaminedStatusCode) {
                    this.workStatues.notExamined++
                } else if (this.totalData[i].formExamineStatus < this.notExaminedStatusCode) {
                    this.workStatues.notSubmitted++
                } else {
                    this.workStatues.alreadyExamined++
                }
            }
        },

        initialize() {
            // console.log("id:")
            // console.log(this.userId)
            this.listLoading = true
            getAllForms({"userId": this.userId}).then(response => {
                console.log(response.data)
                // this.totalData = response.data.items.sort((a, b) => this.cmp(a,b))
                this.totalData = response.data.sort((a, b) => this.cmp(a,b))
                this.getWorkStatues()
                this.filteredData = this.totalData
                this.cities = Array.from(new Set(this.totalData.map(item => item.formCompanyCity)))
                this.cities.splice(0, 0, '全部')
                this.investigations = Array.from(new Set(this.totalData.map(item => item.formInvestigationName)))
                this.investigations.splice(0, 0, '全部')
                this.display()
                this.listLoading = false // 加载完列表就可以认为加载完成
            })
        },

        filterData() {
            this.filteredData = this.totalData.filter(item => {
                if (this.filter.examineStatusCode == 1 && item.formExamineStatus !== this.notExaminedStatusCode) {
                    return false
                }
                if (this.filter.examineStatusCode == 2 && item.formExamineStatus <= this.notExaminedStatusCode) {
                    return false
                }
                if (this.filter.city && this.filter.city !== '全部' && this.filter.city !== item.formCompanyCity) {
                    return false
                }
                if (this.filter.investigation && this.filter.investigation !== '全部' && this.filter.investigation !== item.formInvestigationName) {
                    return false
                }
                if (this.filter.search) {
                    return item.formCompanyName.indexOf(this.filter.search) != -1
                }
                return true
            })
            this.page.totalItems = this.filteredData.length
        },

        display() {
            this.filterData()
            this.showData = this.filteredData.slice((this.page.currentPage - 1) * this.page.pageSize, Math.min(this.page.totalItems, this.page.currentPage * this.page.pageSize))
            // console.log('showing data:')
            // console.log(this.showData)
        },

        passSingle(val) {
            this.selected.selectedItems = [val]
            this.selected.selectedNum = 1
            this.passConfirm.showFlag = true
        },

        passPatch() {
            this.passConfirm.showFlag = true
        },

        passForms(i) {
            if (i < this.selected.selectedNum) {
                passForm(this.selected.selectedItems[i]).then(response => {
                    this.passSuccess = this.passSuccess & response.success
                    this.passForms(i + 1)
                })
            } else {
                if (this.passSuccess) {
                    this.$message({
                        type: 'success',
                        message: '通过成功'
                    })
                }
                this.initialize()
                this.passConfirm.showFlag = false
                this.selected.selectedItems = []
                this.selected.selectedNum = 0
                this.selected.multiSelectFlag = false
                this.$refs.inOrderTable.clearSelection()
                this.passSuccess = false
            }
        },

        pass() {
            this.passSuccess = true
            this.passForms(0)
        },

        showReturnBack() {
            this.returnBackForm.showFlag = true
            this.returnBackForm.data.reason = ''
            this.returnBackForm.data.otherReasonDescription = ''
        },

        returnBackSingle(val) {
            this.selected.selectedItems = [val]
            this.selected.selectedNum = 1
            this.showReturnBack()
        },

        returnBackPatch() {
            this.showReturnBack()
        },

        returnBackForms(i) {
            if (i < this.selected.selectedNum) {
                this.returnBackData.items = this.selected.selectedItems[i]
                this.returnBackData.comments = this.returnBackForm.data
                returnBackForm(this.returnBackData).then(response => {
                    this.returnBackSuccess = this.returnBackSuccess & response.success
                    this.returnBackForms(i + 1)
                })
            } else {
                if (this.returnBackSuccess) {
                    this.$message({
                        type: 'success',
                        message: '退回成功'
                    })
                }
                this.returnBackForm.showFlag = false
                this.initialize()
                this.selected.selectedItems = []
                this.selected.selectedNum = 0
                this.selected.multiSelectFlag = false
                this.$refs.inOrderTable.clearSelection()
                this.returnBackSuccess = false
            }
        },

        returnBack() {
            this.returnBackSuccess = true
            this.returnBackForms(0)
        },

        radio_change(val) {
            // console.log(val)
            this.display()
        },

        selectChange(val) {
            // console.log(val)
            this.display()
        },

        selectByName() {
            // console.log(this.filter.search)
            this.display()
        },

        handleSelectionChange(val) {
            this.selected.selectedNum = val.length;
            this.selected.selectedItems = val;
            this.selected.multiSelectFlag = val.length > 0 ? true : false
            // console.log(this.selected.selectedNum)
            // console.log(this.selected.selectedItems)
        },

        tableRowClassName({ row, rowIndex }) {
            if (rowIndex % 2 == 1) {
                return 'odd-row';
            } else return 'even-row';
        },

		showEdit(entry){
			this.editDialog.showFlag = true
			this.entry = entry
		},

        showForm(val) {
            // console.log(val)
            this.showingForm.showFlag = true
            this.showingForm.data = val
            this.activities = []
            getDataReportFormHistory({formId: val.formID}).then(response => {
                // console.log(response)
                // console.log(this.$refs.leftDiv.clientHeight)
                // this.$refs.rightDiv.clientHeight = this.$refs.leftDiv.clientHeight
                // this.leftDivHeight = this.$refs.leftDiv.clientHeight + 'px'
                // console.log(this.leftDivHeight)
                var histories = response.data
                var len = response.data.length
                for (var i = 0; i < len; ++i) {
                    var historyType = histories[i].historyType
                    this.activities.push({
                        name: this.getHistoryName(historyType),
                        idea: histories[i].historyComment,
                        color: this.getHistoryColor(historyType),
                        timestamp: histories[i].historyDate,
                    })
                }
            })
        },

        getHistoryName(historyType) {
            if (historyType == 0) {
                return "企业提交数据报表"
            } else if (historyType == 1) {
                return "市审核退回"
            } else if (historyType == 2) {
                return "市审核通过"
            } else if (historyType == 3) {
                return "省审核退回"
            } else if (historyType == 4) {
                return "省审核通过"
            }
        },

        getHistoryColor(historyType) {
            if (historyType == 0) {
                return "#4E97FF"
            } else if (historyType == 1 || historyType == 3) {
                return "#dd0000"
            } else if (historyType == 2 || historyType == 4) {
                return "#00dd00"
            }
        },


        changePageSize(val) {
            this.page.pageSize = val;
            this.display();
        },

        changeCurrentPage(val) {
            this.page.currentPage = val;
            this.display();
        },

        tableRowClassName({ row, rowIndex }) {
            if (rowIndex % 2 == 1) {
                return 'odd-row';
            } else {
                return 'even-row'
            };
        },

        getRowKey(row) {
            return row.formID;
        },
    },
}

</script>

<style scoped>
/* .el-table .table_header {
    background-color: rgb(211, 249, 249);
} */

.el-table .odd-row {
    background: white;
}

.el-table .even-row {
    background: rgb(240, 240, 240);
}

/* .el-form-item {
    margin: 10px;
} */

.showInvestigation {
    position: absolute;
    font-size: 15px;
    height: 30px;
    line-height: 30px;
    margin-left: 10px;
}

.formDetailTitle {
    margin-left: 12.5%;
    text-align: center;
    font-size: 30px;
    line-height: 30px;
    height: 50px;
    width: 75%;
    margin-bottom: 10px;
    border-bottom: 1px solid;
}

#examineProgress {
    margin-top: 0px;
    font-size: 23px;
    border-bottom: 1px solid;
    margin-bottom: 0;
    text-align: center;
    width: 100%;
    height: 30px;
    line-height: 23px;
}

#examineProgress :nth-child(2) {
    margin-left: 100px;
}

#examineProgress :nth-child(3) {
    margin-left: 100px;
}

#examineProgress :nth-child(4) {
    margin-left: 100px;
}


.el-table {
    margin-bottom: 15px;
}

.el-pagination {
    text-align: center;
}

.item1 {
    margin-top: 10px;
    margin-bottom: 6px;
}

.item2 {
    margin-bottom: 15px;
}

.dialogDiv2{
    max-height: 300px;
    /* background-color: magenta; */
    float:right;
    display: block;
    overflow-y: scroll;
}
.dialogDiv2::-webkit-scrollbar {display:none}
</style>
